//
//  UserMainController.swift
//  FarmShare
//
//  Created by XingJian Li on 2018/3/15.
//  Copyright © 2018年 aykj. All rights reserved.
//

import Foundation
import Alamofire
class MainMessageIndex: UIViewController {
    

    var tableView  : UITableView!
    
    var MainMessageIndexArray = [MainMessageModel]()


    var bigMainMessageIndexArray = [MainMessageModel]()

    // 顶部刷新
    let header = MJRefreshNormalHeader()
    // 底部刷新
    let footer = MJRefreshAutoNormalFooter()

    var index = 0
   
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = bgGrayColor;
        
        navigationItem.title="消息中心"
        tableView = UITableView(frame:self.view.frame, style:.plain)
        tableView.dataSource = self
        tableView.delegate = self
  
        
        tableView.tableFooterView = UIView.init()
        
        
        tableView.register(NSClassFromString("MainMessageIndexTableViewCell"), forCellReuseIdentifier: "MainMessageIndexTableViewCell")
        
        
        self.view.addSubview(tableView)
        tableView.sd_layout()?.spaceToSuperView(UIEdgeInsets.zero)
        
        
        // 下拉刷新
        header.setRefreshingTarget(self, refreshingAction: #selector(headerRefresh))
        // 现在的版本要用mj_header
        tableView.mj_header = header
        
        tableView.mj_header.beginRefreshing()
        
        // 上拉刷新
        footer.setRefreshingTarget(self, refreshingAction: #selector(footerRefresh))
        tableView.mj_footer = footer
        
        
        
        
        
    }
    
    // 顶部刷新
    @objc func headerRefresh(){
        print("下拉刷新")
        
        self.bigMainMessageIndexArray.removeAll()
        self.MainMessageIndexArray.removeAll()
        
        let manager = UserDefaults()
        
        
        let token: String? = manager.string(forKey:"tokens")  //根据关键字取值
        
        let urlString = "http://wwwqjzsyzcscom.aykj.net.cn/api/supervisenotice/query"
        
        let json = "{\"token\":\"\(token!)\",\"start\":\"\(0)\",\"pageSize\":\"\(5)\"}"
        
        //             let json = "{\"account\":\"\(phoneTextField.text!)\",\"password\":\"\(PasswordTextField.text!)\",\"validateCode\":\"\(verificationTextField.text!)\"}"
        print("json====\(json)")
        
        let url = URL(string: urlString)!
        let jsonData = json.data(using: .utf8, allowLossyConversion: false)!
        
        var request = URLRequest(url: url)
        request.httpMethod = HTTPMethod.post.rawValue
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = jsonData
        
        Alamofire.request(request).responseJSON {(response) in
            
               print("bigDynamicArray====\(response)")
            
            print(response)
            if response.result.isSuccess {
                let json = JSON(response.data!)
                let array = json["resultData"].array
                
                for dataDic in  array! {
                    
                    let model1 =   MainMessageModel()


                    model1.MainMessage = dataDic["description"].string

                    model1.createTime = dataDic["createTime"].string

                    model1.id = dataDic["id"].string
                    
                    model1.isRead = dataDic["isRead"].string
                    
                    model1.informationRecordId = dataDic["informationRecordId"].string
                    
                    
                    self.MainMessageIndexArray.append(model1)
                    
                    
                    
                    
                }
                

                self.bigMainMessageIndexArray.append(contentsOf: self.MainMessageIndexArray)

             
                self.tableView.reloadData()
                
                self.tableView.mj_header.endRefreshing()
            }else{
                self.tableView.mj_header.endRefreshing()
            }
            
        }
        
        
    }
    
    // 底部刷新
    
    @objc func footerRefresh(){
        
        self.MainMessageIndexArray.removeAll()
        
        index += 1
        
        let manager = UserDefaults()
        
        
        let token: String? = manager.string(forKey:"tokens")  //根据关键字取值
        
        let urlString = "http://wwwqjzsyzcscom.aykj.net.cn/api/supervisenotice/query"
        
        let json = "{\"token\":\"\(token!)\",\"start\":\"\(index)\",\"pageSize\":\"\(5)\"}"
        
        //             let json = "{\"account\":\"\(phoneTextField.text!)\",\"password\":\"\(PasswordTextField.text!)\",\"validateCode\":\"\(verificationTextField.text!)\"}"
        print("json====\(json)")
        
        let url = URL(string: urlString)!
        let jsonData = json.data(using: .utf8, allowLossyConversion: false)!
        
        var request = URLRequest(url: url)
        request.httpMethod = HTTPMethod.post.rawValue
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = jsonData
        
        Alamofire.request(request).responseJSON {(response) in
            
            print("bigDynamicArray====\(response)")
            
            print(response)
            if response.result.isSuccess {
                let json = JSON(response.data!)
                let array = json["resultData"].array
                
                for dataDic in  array! {
                    
                    let model1 =   MainMessageModel()
                    
                    
                    model1.MainMessage = dataDic["description"].string
                    
                    model1.createTime = dataDic["createTime"].string
                    
                    model1.id = dataDic["id"].string
                    
                    model1.isRead = dataDic["isRead"].string
                    
                    model1.informationRecordId = dataDic["informationRecordId"].string
                    
                    
                    self.MainMessageIndexArray.append(model1)
                    
                    
                    
                    
                }
                
                
                self.bigMainMessageIndexArray.append(contentsOf: self.MainMessageIndexArray)
                
                
                self.tableView.reloadData()
                
                self.tableView.mj_footer.endRefreshing()
            }else{
                self.tableView.mj_footer.endRefreshing()
            }
            
        }
        
        
        
    }
    
    
    
    
    func loadData(){
        
        
    }
    
    
}
extension MainMessageIndex: UITableViewDelegate, UITableViewDataSource {
    
    
    
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.bigMainMessageIndexArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return 40
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let MessageModel:MainMessageModel = self.bigMainMessageIndexArray[indexPath.row]
        
        let cell = MainMessageIndexTableViewCell(style:UITableViewCellStyle.default, reuseIdentifier: "MainMessageIndexTableViewCell")
        
        
        cell.MainMessageIndexTableViewCell(model: MessageModel)
        cell.selectionStyle = UITableViewCellSelectionStyle.none
        
        return cell
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        
     
        
    }
    
    
}
